# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

#
# Functions to check syntax of X0 command
#

import logging
from .x10codes import *

logger = logging.getLogger()


def checkhu(hu):
    if hu[0].lower() not in iHC:
        logger.error("Error in House Code syntax")
        return False
    if hu[1:] not in iUC:
        logger.error("Error in Unit Code syntax")
        return False
    return True

def checkonoff(onoff):
    if onoff.upper() not in ('ON','OFF'):
        logger.error("Function ON/OFF only")
        return False
    return True

def checkdimb(db):
    if db.upper() not in ('DIM','BRIGHT'):
        logger.error("Function DIM/BRIGHT only")
        return False
    return True

def checklevel(level):
    if level not in range(1,22):
        logger.error("Level 1 to 22")
        return False
    return True

def x10chk(args):
    """
    Check syntax of x10 command
    ONOFF X10 command
    args =[hu,fct]
        fct : 'ON' or 'OFF'
        hu : house hu[0] + unit hu[1] in string format
        hu[0] : 'A'.....'P'
        hu[1:] : '1'.......'16'
    DIMBRIGHT X10 command [hu,fct,level]
        fct : 'DIM' or 'BRIGHT'
        level : range from 1 to 22
    """
    if len(args) < 2:
        return None
    elif len(args) == 2:
        hu,fct = args
        level = None
    else:
        hu,fct,level = args
    if level:
        if not checkdimb(fct) or not checkhu(hu) or not checklevel(level) :
            return None
    else:
        if not checkonoff(fct) or not checkhu(hu):
            return None
    return [hu,fct,level]

